<template>
  <div class="container">
    <!-- 操作按钮 -->
    <div class="actions">
      <button class="btn-add" @click="handleAdd">
        <span class="icon">+</span> 添加教师
      </button>
    </div>

    <!-- 数据表格 -->
    <div class="table-wrapper">
      <table class="data-table">
        <thead>
          <tr>
            <th>ID</th>
            <th>姓名</th>
            <th>职位</th>
            <th>技能</th>
            <th>照片</th>
            <th>简介</th>
            <th>所属学院</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="teacher in teacherList" :key="teacher.id">
            <td>{{ teacher.id }}</td>
            <td>{{ teacher.name }}</td>
            <td>{{ teacher.position }}</td>
            <td>{{ teacher.skill }}</td>
            <td>
              <img 
                v-if="teacher.image" 
                :src="teacher.image" 
                alt="教师照片"
                class="table-image"
              >
              <span v-else>无图片</span>
            </td>
            <td class="td-description">{{ teacher.introduce }}</td>
            <td>{{ teacher.college.college }}</td>
            <td>
              <button class="btn-edit" @click="handleEdit(teacher.id)">编辑</button>
              <button class="btn-delete" @click="handleDelete(teacher.id)">删除</button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 添加/编辑模态框 -->
    <dialog ref="dialogRef" class="modal-dialog">
      <div class="modal-content">
        <h3>{{ modalTitle }}</h3>
        <form @submit.prevent="submitForm">
          <div class="form-group">
            <label>姓名：</label>
            <input v-model="formData.teacher_name" type="text" required>
          </div>
          <div class="form-group">
            <label>职位：</label>
            <input v-model="formData.teacher_position" type="text">
          </div>
          <div class="form-group">
            <label>简介：</label>
            <textarea v-model="formData.teacher_introduce"></textarea>
          </div>
          <div class="form-group">
            <label>技能：</label>
            <input v-model="formData.teacher_skill" type="text">
          </div>
          <div class="form-group">
            <label>所属学院：</label>
            <input v-model="formData.college_name" type="text">
          </div>
          <div class="form-group">
            <label>照片URL：</label>
            <input v-model="formData.teacher_image" type="text">
          </div>
          <div class="form-actions">
            <button type="button" class="btn-cancel" @click="closeModal">取消</button>
            <button type="submit" class="btn-confirm">确认</button>
          </div>
        </form>
      </div>
    </dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import http from '@/http';

const teacherList = ref([]);
const dialogRef = ref(null);
const modalTitle = ref('编辑教师');
const formData = ref({
  teacher_name: '',
  teacher_position: '',
  teacher_introduce: '',
  teacher_skill: '',
  college_name: '',
  teacher_image: '',
  id: null
});

// 初始化加载数据
onMounted(() => {
  fetchTeacherList();
});

// 获取教师列表
const fetchTeacherList = () => {
  http({
    method: 'get',
    url: 'cont/famous/'
  }).then(resp => {
    teacherList.value = resp.data.data;
  }).catch(error => {
    console.error('获取教师列表失败:', error);
    alert('获取教师列表失败，请稍后重试');
  });
};

// 打开添加模态框
const handleAdd = () => {
  modalTitle.value = '添加教师';
  formData.value = {
    teacher_name: '',
    teacher_position: '',
    teacher_introduce: '',
    teacher_skill: '',
    college_name: '',
    teacher_image: '',
    id: null
  };
  dialogRef.value.showModal();
};

// 打开编辑模态框
const handleEdit = (teacherId) => {
  const teacher = teacherList.value.find(t => t.id === teacherId);
  if (teacher) {
    modalTitle.value = '编辑教师';
    formData.value = {
      teacher_name: teacher.name,
      teacher_position: teacher.position,
      teacher_introduce: teacher.introduce,
      teacher_skill: teacher.skill,
      college_name: teacher.college.college,
      teacher_image: teacher.image,
      id: teacher.id
    };
    dialogRef.value.showModal();
  }
};

// 删除教师
const handleDelete = (teacherId) => {
  if (confirm('确定要删除该教师吗？')) {
    http({
      method: 'DELETE',
      url: `cont/famous/${teacherId}/`
    }).then(() => {
      alert('删除成功');
      fetchTeacherList();
    }).catch(error => {
      console.error('删除失败:', error);
      alert(error?.response?.data?.message || '删除失败，请稍后重试');
    });
  }
};

// 提交表单
const submitForm = () => {
  const requiredFields = [
    formData.value.teacher_name,
    formData.value.teacher_position,
    formData.value.teacher_introduce,
    formData.value.college_name,
    formData.value.teacher_skill,
    formData.value.teacher_image
  ];
  
  if (!requiredFields.every(Boolean)) {
    alert('请填写所有必填字段');
    return;
  }

  let apiUrl, method;
  if (modalTitle.value === '添加教师') {
    apiUrl = 'cont/famous/';
    method = 'POST';
  } else {
    apiUrl = `cont/famous/${formData.value.id}/`;
    method = 'PUT';
  }

  http({
    method,
    url: apiUrl,
    data: formData.value
  }).then(() => {
    alert(modalTitle.value === '添加教师' ? '添加成功' : '编辑成功');
    closeModal();
    fetchTeacherList();
  }).catch(error => {
    console.error('提交失败:', error);
    alert(error?.response?.data?.message || '提交失败，请稍后重试');
  });
};

// 关闭模态框
const closeModal = () => {
  dialogRef.value.close();
};
</script>

<style scoped>
/* 使用与第一个示例完全相同的样式 */
.container {
  padding: 20px;
  font-family: Arial, sans-serif;
  color: #333;
}

.actions {
  margin-bottom: 20px;
}

.btn-add {
  background-color: #4CAF50;
  color: white;
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  font-size: 14px;
}

.btn-add:hover {
  background-color: #45a049;
}

.icon {
  margin-right: 5px;
  font-weight: bold;
}

.table-wrapper {
  width: 100%;
  overflow-x: auto;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 10px;
  font-size: 14px;
}

.data-table th, 
.data-table td {
  border: 1px solid #ddd;
  padding: 12px;
  text-align: center;
  vertical-align: middle;
}

.data-table th {
  background-color: #f8f8f8;
  font-weight: bold;
  color: #333;
}

.data-table tr:nth-child(even) {
  background-color: #f9f9f9;
}

.data-table tr:hover {
  background-color: #f1f1f1;
}

.td-description {
  max-width: 200px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.table-image {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
  border: 1px solid #eee;
}

.btn-edit, .btn-delete {
  padding: 6px 12px;
  margin: 0 2px;
  border: none;
  border-radius: 3px;
  cursor: pointer;
  font-size: 13px;
}

.btn-edit {
  background-color: #2196F3;
  color: white;
}

.btn-delete {
  background-color: #f44336;
  color: white;
}

.btn-edit:hover {
  background-color: #0b7dda;
}

.btn-delete:hover {
  background-color: #da190b;
}

.modal-dialog {
  align-self: center;
  justify-self:center;
  width: 80%;
  max-width: 600px;
  border: none;
  border-radius: 6px;
  padding: 0;
  box-shadow: 0 3px 9px rgba(0,0,0,0.3);
}

.modal-dialog::backdrop {
  background: rgba(0, 0, 0, 0.5);
}

.modal-content {
  padding: 20px;
}

.modal-content h3 {
  margin-top: 0;
  color: #333;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
  color: #555;
}

.form-group input,
.form-group textarea {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  box-sizing: border-box;
}

.form-group textarea {
  height: 80px;
  resize: vertical;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
  padding-top: 15px;
  border-top: 1px solid #eee;
}

.btn-confirm, .btn-cancel {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.btn-confirm {
  background-color: #4CAF50;
  color: white;
}

.btn-cancel {
  background-color: #f44336;
  color: white;
}

.btn-confirm:hover {
  background-color: #45a049;
}

.btn-cancel:hover {
  background-color: #da190b;
}

@media (max-width: 768px) {
  .data-table {
    font-size: 13px;
  }
  
  .data-table th, 
  .data-table td {
    padding: 8px;
  }
  
  .btn-edit, .btn-delete {
    padding: 4px 8px;
    font-size: 12px;
  }
}
</style>